package com.lishe.lishe.lishe.module.excitation.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerviewBaseAdapter;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.excitation.adapter.PersonAchievementListAdapter;
import com.lishe.lishe.lishe.module.excitation.bean.AchievementObject;
import com.lishe.lishe.lishe.module.excitation.bean.MineExcitationObject;
import com.lishe.lishe.lishe.bean.SpaceItemDecoration;
import com.lishe.lishe.lishe.module.excitation.dialog.AchievementCompleteDialog;
import com.lishe.lishe.lishe.module.excitation.dialog.AchievementGetSuccessDialog;
import com.lishe.lishe.lishe.module.excitation.dialog.AchievementGiveTimeDialog;
import com.lishe.lishe.lishe.module.excitation.dialog.AchievementLightUpDialog;
import com.lishe.lishe.lishe.module.excitation.dialog.AchievementNotCompleteDialog;
import com.lishe.lishe.lishe.module.excitation.http.HttpExcitation;
import com.lishe.lishe.lishe.module.excitation.interfaces.OnAchievementCompleteListener;
import com.lishe.lishe.lishe.module.excitation.presenter.MinePresenter;
import com.lishe.lishe.lishe.utils.BitmapUtils;
import com.lishe.lishe.lishe.utils.Utils;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.ResponseHandlerInterface;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.socialize.UMShareAPI;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by yang on 2017/10/27.
 * 个人成就
 */

public class PersonAchievementActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = PersonAchievementActivity.class.getSimpleName();
    private static final String WeChat = "WeChat";//微信聊天：WeChat，
    private static final String WeShare = "WeShare";//微信朋友圈：WeShare，
    private static final String QQChat = "QQChat";//QQ聊天：QQChat，
    private static final String QQShare = "QQShare";//QQ朋友圈：QQShare


    public static void jump(Activity activity, String userId) {
        Intent intent = new Intent(activity, PersonAchievementActivity.class);
        intent.putExtra("mUserId", userId);
        activity.startActivity(intent);
    }

    private Button mBack;
    private TextView mTitle, mEmptyText;
    private RecyclerView mRecycleView;
    private RelativeLayout mEmpty, mError;
    private SmartRefreshLayout mSmartRefreshLayout;

    private List<MineExcitationObject> mList;
    private PersonAchievementListAdapter mAdapter;
    private String mUserId = null;
    private AchievementObject mAchievementObject;//表示当前正在获取的成就详情
    private int num=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_achievement);
        mUserId = getIntent().getStringExtra("mUserId");
        initView();
        initListener();
        initAdapter();
        setSmartRefreshLayout();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(PersonAchievementActivity.this).onActivityResult(requestCode, resultCode, data);
        Log.e(TAG, "requestCode = " + requestCode + " , resultCode = " + resultCode);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initView() {
        mBack = findViewById(R.id.title_left_button);
        mTitle = findViewById(R.id.title_text_title);
        mRecycleView = findViewById(R.id.list);
        mEmpty = findViewById(R.id.empty);
        mError = findViewById(R.id.error);
        mEmptyText = findViewById(R.id.empty_text);
        mSmartRefreshLayout = findViewById(R.id.refreshlayout);

        mRecycleView.setLayoutManager(new GridLayoutManager(PersonAchievementActivity.this, 3));
        mRecycleView.addItemDecoration(new SpaceItemDecoration(0, Utils.dip2px(PersonAchievementActivity.this, 10), Utils.dip2px(PersonAchievementActivity.this, 10), Utils.dip2px(PersonAchievementActivity.this, 10)));

        if (TextUtils.isEmpty(mUserId) || mUserId.equals(Globals.getExcatationUserId())) {
            mTitle.setText(R.string.my_achievement);
        } else {
            mTitle.setText(R.string.ta_achievement);
        }

        mEmptyText.setText("还没有获得成就哦~");
    }

    private void initListener() {
        mBack.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                finish();
                break;
        }
    }

    private void initAdapter() {
        mList = new ArrayList<>();

        mAdapter = new PersonAchievementListAdapter(PersonAchievementActivity.this, mList, BitmapUtils.getDisplayWidth(this));
        mAdapter.setOnItemClickListener(new RecyclerviewBaseAdapter.ItemListener.ItemClickListener() {
            @Override
            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
                Log.e(TAG, "position==" + position);
                if (TextUtils.isEmpty(mUserId) || mUserId.equals(Globals.getExcatationUserId())) {
                    getAchieveDetail(mList.get(position).getAchieveId());
                }
            }
        });
        mRecycleView.setAdapter(mAdapter);
    }

    private void setSmartRefreshLayout() {
        mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
        mSmartRefreshLayout.setEnableLoadmore(false);//默认设置不能加载更多

        mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getAchievement();
            }
        });
    }


    /**
     * 获取个人成就列表
     */
    public void getAchievement() {
        if (mEmpty.getVisibility() == View.VISIBLE) {
            mEmpty.setVisibility(View.GONE);
        }

        if (mError.getVisibility() == View.VISIBLE) {
            mError.setVisibility(View.GONE);
        }
        try {
            MinePresenter.getInstance().getUserAchieveList(Globals.getToken(), mUserId,num, new DataResponseListener<List<MineExcitationObject>>() {
                @Override
                public void onSuccess(List<MineExcitationObject> dataResponse) {
                    mSmartRefreshLayout.finishRefresh(500, true);

                    mList.clear();
                    mList.addAll(dataResponse);
                    mAdapter.notifyDataSetChanged();
                    if (mList.size() == 0) {
                        mEmpty.setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void onFail(String failMessage) {
                    mSmartRefreshLayout.finishRefresh(1000, false);

                    if (mList.size() == 0) mEmpty.setVisibility(View.VISIBLE);
                    toast(failMessage);
                }

                @Override
                public void onError(Throwable e) {
                    mSmartRefreshLayout.finishRefresh(1000, false);

                    if (mList.size() == 0) mEmpty.setVisibility(View.VISIBLE);
                    toast(R.string.network_or_server_exception);
                }
            });
        } catch (Exception e) {
            mSmartRefreshLayout.finishRefresh(1000, false);

            e.printStackTrace();
            if (mList.size() == 0) mEmpty.setVisibility(View.VISIBLE);
            toast(getString(R.string.data_parse_fail));
        }

    }

    /**
     * 获取成就详情
     */
    private void getAchieveDetail(String achieveId) {
        try {
            MinePresenter.getInstance().getAchieveDetail(Globals.getToken(), mUserId, achieveId, new DataResponseListener<AchievementObject>() {

                @Override
                public void onPrepare() {
                    super.onPrepare();
                    getDefaultProgressDialogs("加载中...", false);
                }

                @Override
                public void onSuccess(AchievementObject dataResponse) {
                    dismissProgressDialogs();
                    mAchievementObject = dataResponse;
                    showDialogs();
                }

                @Override
                public void onFail(String failMessage) {
                    dismissProgressDialogs();
                    toast(failMessage);
                }

                @Override
                public void onError(Throwable e) {
                    dismissProgressDialogs();
                    toast(R.string.network_or_server_exception);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            dismissProgressDialogs();
            toast(getString(R.string.data_parse_fail));
        }
    }

    /**
     * 领取奖励
     */
    private void receiveAchieveReward(int achieveId) {
        try {
            MinePresenter.getInstance().receiveAchieveAward(Globals.getToken(), mUserId, String.valueOf(achieveId), new DataResponseListener() {
                @Override
                public void onSuccess(Object dataResponse) {
                    showGetSuccessDialog();
                    mAchievementObject.setReceivedRewardFlag(1);
                }

                @Override
                public void onFail(String failMessage) {
                    toast(failMessage);
                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    toast(R.string.network_or_server_exception);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            toast(getString(R.string.data_parse_fail));
        }
    }

    private void showDialogs() {
        if (mAchievementObject != null) {
            if (!(mAchievementObject.getAchievedTime() == 0 && (TextUtils.isEmpty(mAchievementObject.getUserId()) || mAchievementObject.getUserId().equals("0")))) {//成就已获得
                if (mAchievementObject.getAchieveType().equals("1") || mAchievementObject.getAchieveType().equals("4")) {//1:基础成就 4:行为成就
                    if (mAchievementObject.getHadCount() >= mAchievementObject.getAdmireCount()) {    //已获得鼓励数大于等于获得成就所需鼓励数
                        if (mAchievementObject.getReceivedRewardFlag() == 0) { //receivedRewardFlag=0 表示奖励未领取
                            showCompleteDialogs();
                        } else if (mAchievementObject.getReceivedRewardFlag() == 1) {//receivedRewardFlag=1 表示奖励已领取
                            showGiveTimeDialogs();
                        }
                    } else {//未获得成就
                        showNotCompleteDialogs();
                    }
                } else {//3：指标成就 2：目标成就
                    if (mAchievementObject.getReceivedRewardFlag() == 0) { //receivedRewardFlag=0 表示奖励未领取
                        showCompleteDialogs();
                    } else if (mAchievementObject.getReceivedRewardFlag() == 1) {//receivedRewardFlag=1 表示奖励已领取
                        showGiveTimeDialogs();
                    }
                }
            } else {//成就未获得
                if (mAchievementObject.getAchieveType().equals("3") || mAchievementObject.getAchieveType().equals("2")) {//3：指标成就 2：目标成就
                    showLightUpDialogs();
                } else {
                    showNotCompleteDialogs();
                }
            }
        }

    }

    /**
     * 展示获得成就dialog
     */
    private void showCompleteDialogs() {
        AchievementCompleteDialog.Builder builder = new AchievementCompleteDialog.Builder(PersonAchievementActivity.this);
        builder.setAchievementObject(mAchievementObject);
        builder.setOnAchievementCompleteListener(new OnAchievementCompleteListener() {
            @Override
            public void getRewards(Dialog dialog, int achieveId) {
                Log.e(TAG, "领取奖励：" + achieveId);
                receiveAchieveReward(achieveId);
                if (dialog != null) {
                    dialog.dismiss();
                }
            }

            @Override
            public void showOff(Dialog dialog, int achieveId) {
                Log.e(TAG, "炫耀一下：" + achieveId);
                PersonShareAchievementActivity.jump(PersonAchievementActivity.this, mAchievementObject);
                dialog.dismiss();
            }
        });
        builder.show();
    }

    /**
     * 展示获得成就dialog
     */
    private void showNotCompleteDialogs() {
        AchievementNotCompleteDialog.Builder builder = new AchievementNotCompleteDialog.Builder(PersonAchievementActivity.this);
        builder.setAchievementObject(mAchievementObject);
        builder.show();
    }

    /**
     * 展示子成就dialog
     */
    private void showLightUpDialogs() {
        AchievementLightUpDialog.Builder builder = new AchievementLightUpDialog.Builder(PersonAchievementActivity.this);
        builder.setAchievementObject(mAchievementObject);
        builder.show();
    }


    /**
     * 展示成就时间dialog
     */
    private void showGiveTimeDialogs() {
        AchievementGiveTimeDialog.Builder builder = new AchievementGiveTimeDialog.Builder(PersonAchievementActivity.this);
        builder.setAchievementObject(mAchievementObject);
        builder.show();
    }

    /**
     * 展示领取奖励成功
     */
    private void showGetSuccessDialog() {
        AchievementGetSuccessDialog.Builder builder = new AchievementGetSuccessDialog.Builder(PersonAchievementActivity.this);
        builder.show();
    }

}
